<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - Online Judge</title>
    <link rel="stylesheet" href="/css/user.css">
</head>

<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <h1>📚 Online Judge</h1>
        <div class="nav-links">
            <a href="/all_questions">题目列表</a>
            <a href="/ranking.html">排行榜</a>
        </div>
        <div class="user-info" id="userInfo" style="display: none;">
            <span>欢迎，<span class="username" id="navUsername"></span></span>
            <button onclick="logout()">登出</button>
        </div>
        <div id="loginLink">
            <a href="/login.html">登录</a>
        </div>
    </nav>

    <!-- 用户信息卡片 -->
    <div class="container">
        <div class="user-card">
            <h2 id="displayUsername">加载中...</h2>
            <p id="userEmail"></p>
            <div class="user-stats">
                <div class="stat-item">
                    <div class="number" id="totalSubmit">0</div>
                    <div class="label">总提交</div>
                </div>
                <div class="stat-item">
                    <div class="number" id="acceptedCount">0</div>
                    <div class="label">通过数</div>
                </div>
                <div class="stat-item">
                    <div class="number" id="acRate">0%</div>
                    <div class="label">通过率</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 提交历史 -->
    <div class="submission-history">
        <h2>提交历史</h2>
        <div id="submissionHistoryContent">
            <p class="loading">加载中...</p>
        </div>
    </div>

    <script src="/js/auth.js"></script>
    <script>
        // 检查登录状态
        // 这个是可以直接执行的
        if (!isLoggedIn()) {
            alert('请先登录');
            window.location.href = '/login.html';
        }

        // 加载用户信息
        async function loadUserInfo() {
            const user = getUserInfo();
            const userId = user.user_id;

            try {
                // 调用后端获取用户详细信息
                const response = await fetch(`${API_BASE}/user/${userId}`, {
                    headers: getAuthHeaders()
                });
                
                const result = await response.json();
                
                if (result.status === 0) {
                    const userData = result.user;
                    
                    // 更新页面显示
                    document.getElementById('displayUsername').textContent = userData.username;
                    document.getElementById('userEmail').textContent = userData.email || '未设置邮箱';
                    document.getElementById('totalSubmit').textContent = userData.total_submit;
                    document.getElementById('acceptedCount').textContent = userData.accepted_count;
                    
                    // 计算通过率
                    const acRate = userData.total_submit > 0 
                        ? ((userData.accepted_count / userData.total_submit) * 100).toFixed(1)
                        : 0;
                    document.getElementById('acRate').textContent = acRate + '%';
                    
                } else {
                    alert('获取用户信息失败');
                    logout();
                }
            } catch (error) {
                console.error('Load user info error:', error);
                alert('网络错误，请刷新重试');
            }
        }

        // 加载提交历史记录
        async function loadSubmissionHistory() {
            const user = getUserInfo();
            const userId = user.user_id;

            try {
                // 调用后端API获取提交记录
                const response = await fetch(`${API_BASE}/submissions/${userId}`, {
                    headers: getAuthHeaders()
                });

                const result = await response.json();
                console.log('提交记录返回结果:', result);

                if (result.status === 0) {
                    const submissions = result.submissions;
                    
                    if (submissions && submissions.length > 0) {
                        // 渲染提交记录表格
                        renderSubmissionTable(submissions);
                    } else {
                        document.getElementById('submissionHistoryContent').innerHTML = 
                            '<p>暂无提交记录</p>';
                    }
                } else {
                    document.getElementById('submissionHistoryContent').innerHTML = 
                        `<p style="color: red;">加载失败: ${result.msg || '未知错误'}</p>`;
                }
            } catch (error) {
                console.error('Load submission history error:', error);
                document.getElementById('submissionHistoryContent').innerHTML = 
                    '<p style="color: red;">网络错误，请刷新重试</p>';
            }
        }

        // 渲染提交记录表格
        function renderSubmissionTable(submissions) {
            let tableHTML = `
                <table class="submission-table">
                    <thead>
                        <tr>
                            <th>题目编号</th>
                            <th>状态</th>
                            <th>提交时间</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            submissions.forEach(submission => {
                // 格式化状态显示
                const statusText = formatStatus(submission.status);
                const statusClass = getStatusClass(submission.status);
                
                // 不需要格式化时间显示
                const submitTime = submission.submit_time;

                tableHTML += `
                    <tr>
                        <td>${submission.question_number}</td>
                        <td class="${statusClass}">${statusText}</td>
                        <td>${submitTime}</td>
                    </tr>
                `;
            });

            tableHTML += `
                    </tbody>
                </table>
            `;

            document.getElementById('submissionHistoryContent').innerHTML = tableHTML;
        }

        // 格式化状态文本
        function formatStatus(status) {
            const statusMap = {
                0: '未通过',
                1: '通过',
                // 2: '运行中',
                // 3: '通过',
                // 4: '答案错误',
                // 5: '运行时错误',
                // 6: '超时',
                // 7: '内存超限',
                // 8: '编译错误',
                // 9: '系统错误'
            };
            // return statusMap[status] || `未知状态(${status})`;
            return statusMap[status] || `未知状态`;
        }

        // 获取状态对应的CSS类
        function getStatusClass(status) {
            if (status === 1) return 'status accepted';  // 通过
            if (status === 0) return 'status not accpeted';  // 未通过
            return 'status wrong';  // 其他错误状态
        }


        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', () => {
            loadUserInfo();
            loadSubmissionHistory();
        });
    </script>
</body>
</html>